<template>
  <div class="enterprise">
    <div v-if="!showEntDetail">
      <el-card>
        <el-form inline :model="pageParams">
          <el-form-item label="企业名称">
            <el-input size="small" placeholder="请输入企业名称" v-model="pageParams.name"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button size="small" icon="el-icon-search" type="primary" @click="handleSearch">查询</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card>
        <el-button size="small" icon="el-icon-plus" type="primary" @click="handleAdd">添加企业</el-button>
        <el-table border size="small" stripe :header-cell-style="{ backgroundColor: '#f4f6f8' }" :data="enterpriseList" v-loading="loading" element-loading-text="拼命加载中" @expand-change="expandChange">
          <el-table-column type="expand">
            <template #default="{row}">
              <contract-table :contract-list="row.list" :enterpriseId="enterpriseId"></contract-table>
            </template>
          </el-table-column>
          <el-table-column label="序号" type="index" align="center"></el-table-column>
          <el-table-column label="企业名称" prop="name" align="center"></el-table-column>
          <el-table-column label="联系人" prop="contact" align="center"></el-table-column>
          <el-table-column label="联系电话" prop="contactNumber" align="center"></el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="{row}">
              <el-button type="text" @click="handleAddContract(row)">添加合同</el-button>
              <el-button type="text" @click="handleShow(row)">查看</el-button>
              <el-button type="text" @click="handleEdit(row)">编辑</el-button>
              <el-button type="text" @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageParams.page" :page-sizes="[15, 20, 30, 40]" :page-size="pageParams.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" background></el-pagination>

        <el-dialog append-to-body :title="title" :visible.sync="dialogVisible" @close="$refs.enterpriseForm.resetForm()">
          <enterprise-form :edit="edit" @success="handleSuccess" ref="enterpriseForm"></enterprise-form>
        </el-dialog>

        <el-drawer title="添加合同" :visible.sync="drawerVisible" @close="$refs.contractForm.resetForm()">
          <contract-form :enterpriseId="enterpriseId" @success="handleSuccess" ref="contractForm"></contract-form>
        </el-drawer>

      </el-card>
    </div>
    <EntDetail v-else ref="entDetailRef" @back="showEntDetail=false"></EntDetail>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import EnterpriseForm from '@/views/park/enterprise/components/enterpriseForm.vue';
import ContractForm from '@/views/park/enterprise/components/contractForm.vue';
import ContractTable from '@/views/park/enterprise/components/contractTable.vue';
import EntDetail from '@/views/park/enterprise/components/entDetail.vue';

export default {
  name: 'enterprise',
  components: { EntDetail, ContractTable, ContractForm, EnterpriseForm },
  data() {
    return {
      /* 获取企业列表的分页参数 */
      pageParams: {
        page: 1,
        pageSize: 15,
        name: undefined,
      },
      /* 加载企业列表的loading状态 */
      loading: false,
      /* 是否处于编辑状态 */
      edit: false,
      /* 是否显示添加和编辑企业的弹框 */
      dialogVisible: false,
      /* 是否显示添加合同的抽屉 */
      drawerVisible: false,
      /* 当前的企业ID */
      enterpriseId: null,
      showEntDetail: false,
      entDetailRef: null,
    };
  },
  methods: {
    /* 获取企业列表的回调函数 */
    async fetchEnterpriseList() {
      try {
        this.loading = true;
        await this.$store.dispatch('enterpriseStore/fetchEnterpriseList', this.pageParams);
      } catch (error) {
        this.$message.error(error.message);
      } finally {
        this.loading = false;
      }
    },
    /* 分页器一页展示的数据条数发生变化的回调函数 */
    handleSizeChange(pageSize) {
      this.pageParams.pageSize = pageSize;
      this.fetchEnterpriseList();
    },
    /* 分页器当前页发生变化的回调函数 */
    handleCurrentChange(page) {
      this.pageParams.page = page;
      this.fetchEnterpriseList();
    },
    /* 点击查询按钮的回调函数 */
    handleSearch() {
      this.pageParams.page = 1;
      this.fetchEnterpriseList();
    },
    /* 点击删除按钮的回调函数 */
    async handleDelete(row) {
      const confirm = await this.$confirm(`删除${row.name}, 是否继续?`, '提示', { type: 'warning' }).catch(error => error);
      if (confirm === 'cancel') return;
      try {
        const deleteResult = await this.$store.dispatch('enterpriseStore/deleteEnterprise', row.id);
        this.$message.success(deleteResult);
        this.fetchEnterpriseList();
      } catch (error) {
        this.$message.error(error.message);
      }
    },
    /* 点击添加按钮的回调函数 */
    handleAdd() {
      this.dialogVisible = true;
      this.edit = false;
    },
    /* 点击编辑按钮的回调函数 */
    handleEdit(row) {
      this.dialogVisible = true;
      this.edit = true;
      this.$nextTick(() => {
        this.$refs.enterpriseForm.findEnterprise(row.id);
      });
    },
    handleSuccess() {
      this.dialogVisible = false;
      this.drawerVisible = false;
      this.fetchEnterpriseList();
    },
    /* 点击添加合同按钮的函数 */
    handleAddContract(row) {
      this.enterpriseId = row.id;
      this.drawerVisible = true;
    },
    /*
   * 当用户对某一行展开或者关闭的时候会触发该事件（展开行时，回调的第二个参数为 expandedRows；树形表格时第二参数为 expanded）
   *  */
    async expandChange(row, expandedRows) {
      const enterprise = expandedRows.find(item => item.id === row.id);
      if (!enterprise) return;
      try {
        this.enterpriseId = row.id;
        await this.$store.dispatch('enterpriseStore/fetchContractList', row.id);
      } catch (error) {
        this.$message.error(error.message);
      }
    },

    /* 点击查看按钮的回调函数 */
    handleShow(row) {
      this.showEntDetail = true;
      this.$nextTick(() => {
        this.$refs.entDetailRef.findEnterprise(row.id);
      });
    },

  },
  computed: {
    ...mapGetters('enterpriseStore', ['enterpriseList', 'total']),
    title() {
      return this.edit ? '编辑企业' : '添加企业';
    },
  },
  mounted() {
    this.fetchEnterpriseList();
  },
};
</script>

<style scoped lang="scss">
.enterprise {
  padding: 15px;

  .el-card {
    margin-bottom: 10px;

    .el-form-item {
      margin-bottom: unset;
    }

    .el-table {
      margin: 10px 0;
    }

    .el-pagination {
      display: flex;
      justify-content: center;
    }

    ::v-deep .el-dialog__body {
      display: flex;
      justify-content: center;
    }

    ::v-deep .el-drawer__body {
      display: flex;
      justify-content: center;
    }
  }
}
</style>
